//
//  SystemMessageViewController.m
//  CYWFrame
//
//  Created by Macx on 2017/9/28.
//  Copyright © 2017年 Macx. All rights reserved.
//

#import "SystemMessageViewController.h"
#import "ReplyCommentViewController.h"
#import "QADetailViewController.h"
#import "SystemMessageCell.h"
#import "NotificationModel.h"

@interface SystemMessageViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, assign) NSInteger page; // 网络请求页数
@property (nonatomic, strong) NSMutableArray *infoArr;

@end

@implementation SystemMessageViewController {
    UITableView     *_tableView;
    SystemMessageCell *_cell;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.page = 1;
    
    [self GETMessageList];
    
    [self buildUI];
    
    [self refreshData];
    
    
    
}

#pragma mark ==========构建UI==========
- (void)buildUI {
    
//    self.view.backgroundColor = UISeparatedColorRGB;
    
    self.navigationItem.title = @"系统消息";
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    _tableView.backgroundColor = UISeparatedColorRGB;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.tableFooterView = [[UIView alloc]init];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [_tableView registerNib:[UINib nibWithNibName:@"SystemMessageCell" bundle:nil] forCellReuseIdentifier:@"message"];
    
}

#pragma mark ==========更新数据==========
- (void)refreshData {
    __weak typeof (self) weakSelf = self;
    
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        NSLog(@"下拉刷新");
        weakSelf.page = 1;
        [weakSelf GETMessageList];
    }];
    
    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        NSLog(@"上拉加载");
        weakSelf.page++;
        [weakSelf GETMessageList];
    }];
    
}


#pragma mark ==========UITableView==========
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    _cell = [tableView dequeueReusableCellWithIdentifier:@"message"];
    
    _cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    NotificationModel *model = self.infoArr[indexPath.row];
    
    _cell.model = model;
    
//    User *model = self.infoArr[indexPath.row];
//    
//    _cell.model = model;
//    
//    _cell.focus.tag = indexPath.row+1;
//    [_cell.focus addTarget:self action:@selector(focusClick:) forControlEvents:UIControlEventTouchUpInside];
    
    _cell.contentBgView.tag = indexPath.row+1;
    [_cell.contentBgView addTarget:self action:@selector(pushQuestionClick:)];
    
    return _cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.infoArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat cellH = [_cell cellHeight];
    if (cellH == 0) {
        return 10;
    }
    else
        return [_cell cellHeight];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSLog(@"点击tableView.cell = %ld", indexPath.row);
}


#pragma mark ===========响应方法==========
/**
 获取资讯列表
 */
- (void)GETMessageList {
    
    // GET /articles 获取（查询）资讯列表 keyword 关键词，匹配商品名 page 页码，默认为1 per_page 每页显示数，默认为10 cate_id 二级分类ID，暂不支持一级分类搜索 orderby 排序字段
    
    NSDictionary *param = @{@"page":[NSString stringWithFormat:@"%ld", self.page],
                            @"per_page":@"10"};
    
    [[NetworkTool sharedTool] requestWithName:@"获取系统消息" URLString:APINotifications parameters:param method:@"GET" callBack:^(id responseObject) {
    
        NSArray *arr = responseObject[@"data"];
        
        if (arr.count == 0) {
            [_tableView.mj_header endRefreshing];
            [_tableView.mj_footer endRefreshing];
            self.page--;
            return ;
        }
        
        if (self.page == 1) {
            [self.infoArr removeAllObjects];
        }
        
        for (NSDictionary *dic in arr) {
            NotificationModel *model = [[NotificationModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.infoArr addObject:model];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [_tableView.mj_header endRefreshing];
            [_tableView.mj_footer endRefreshing];
            [_tableView reloadData];
        });
    }];
    
}

- (void)pushQuestionClick:(UIView *)sender {
    
//    NSLog(@"%ld", sender.tag);
    UITapGestureRecognizer *tapRecognizer = (UITapGestureRecognizer
                                             *)sender;
    NSString *index = [NSString stringWithFormat:@"%ld", [tapRecognizer.view tag]];
    NSLog (@"%@", index);
    
    NotificationModel *model = self.infoArr[[index integerValue]-1];
    
    if ([model.extra isKindOfClass:[NSDictionary class]]) {
    
    
        NSDictionary *dict = model.extra;
        if ([[model.extra valueForKey:@"action"] isEqualToString:@"inviteAnswer"]) {
            QADetailViewController *detailVC = [[QADetailViewController alloc] init];
            detailVC.answerId = dict[@"data"][@"question_id"];
            [self.navigationController pushViewController:detailVC animated:YES];
        }
        else if ([[dict valueForKey:@"action"] isEqualToString:@"openQuestion"]) {
            ReplyCommentViewController *replyVC = [[ReplyCommentViewController alloc] init];
            replyVC.questionId = [dict[@"data"][@"question_id"] integerValue];
            replyVC.type = 3;
            [self.navigationController pushViewController:replyVC animated:YES];
        }
        else if ([[dict valueForKey:@"action"] isEqualToString:@"openAnswer"]) {
            ReplyCommentViewController *replyVC = [[ReplyCommentViewController alloc] init];
            replyVC.questionId = [dict[@"data"][@"answer_id"] integerValue];
            replyVC.type = 3;
            [self.navigationController pushViewController:replyVC animated:YES];
        }

    }
}

// 懒加载
- (NSMutableArray *)infoArr {
    if (_infoArr == nil) {
        _infoArr = [[NSMutableArray alloc] init];
    }
    return _infoArr;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
